﻿/// <summary>
/// data   :2016-05-17
/// author :fanzhengyong
/// 负责AB文件的加载，以及资源获取
/// </summary>
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine.UI;

namespace UEngine
{
    //public enum ResourceType
    //{
    //    None,   // 无
    //    Data,   // 策划数据
    //    Effect, // 特效
    //    Model,  // 模型
    //    Music,  // 背景音乐
    //    Scene,  // 场景
    //    Sound,  // 音效
    //    UI,     // 界面
    //    Misc,   // 其他
    //}

    public class ResourceManager
    {
        private static ResourceManager m_instance = null;

        public static ResourceManager Instance()
        {
            if (m_instance == null)
            {
                m_instance = new ResourceManager();
            }
            return m_instance;
        }

        private string              m_resDirRoot = null;
        private AssetBundleManifest m_manifest   = null;
        public bool Init()
        {
            //m_streamDirBundleList = new AssetBoundList(m_streamDirBundleListPath);
            //m_AppDirBundleList = new AssetBoundList(m_AppDirBundleListPath);
            
            //if (Application.platform == RuntimePlatform.Android || Application.isMobilePlatform) 
            //{
            //    return true;
            //}

#if UNITY_ANDROID
		    m_resDirRoot = "file://" + Application.persistentDataPath;
           
#elif UNITY_IPHONE
            m_resDirRoot = Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
            m_resDirRoot = "file:///" + Application.persistentDataPath;
            m_resDirRoot = Application.streamingAssetsPath;
#endif

            string path = m_resDirRoot + "/" + "StreamingAssets";
            byte [] fileData = FileHelper.ReadFromFile(path);
            if (fileData != null && fileData.Length > 0)
            {
                AssetBundle bundle = AssetBundle.LoadFromMemory(fileData);
                m_manifest = bundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
            }
            else
            {
                Debug.LogErrorFormat("manifest not found ({0})" + path);
            }
            return m_manifest != null;
        }

        public T LoadResource<T>(string path) where T : UnityEngine.Object
        {
            return LoadResource<T>(GetDirectoryName(path), GetFileName(path));
        }

        public UnityEngine.Object LoadResource(string path, string name)
        {
            return LoadResource<UnityEngine.Object>(path, name);
        }

        public UnityEngine.Object LoadResource(string path)
        {
            return LoadResource<UnityEngine.Object>(GetDirectoryName(path), GetFileName(path));
        }

        public Sprite LoadUISprite(string path)
        {
            return LoadResource<Sprite>("UI/" + path);
        }

        public GameObject LoadUIResource(string path)
        {
            return LoadResource<GameObject>("UI/" + path, GetFileName(path));
        }

        public GameObject LoadModelResource(string path)
        {
            return LoadResource<GameObject>("Model/" + path, GetFileName(path));
        }

        public GameObject LoadEffectResource(string path)
        {
            return LoadResource<GameObject>("Effects/" + path, GetFileName(path));
        }

        public TextAsset LoadDataResource(string path)
        {
            return LoadResource<TextAsset>("Data/" + path);
        }

        public Sprite LoadIconResource(string path)
        {
            return LoadResource<Sprite>("Icon/" + path);
        }

        private AssetBundle LoadAssetBundle(string path, bool cascade = true)
        {
            //AssetBundleInfo bundleInfo = null;
            //if (!bundleCache.TryGetValue(path, out bundleInfo))
            //{
            //    string assetBundleName = path;
            //    var bytes = IOUtils.ReadFromFile(path);
            //    if (bytes != null && bytes.Length > 0)
            //    {
            //        if (cascade)
            //        {
            //            LoadDependencies(assetBundleName);
            //        }
            //        if (isCompressed)
            //        {
            //            bytes = CompressUtils.DecompressLZMA(bytes);
            //        }
            //        var bundle = AssetBundle.LoadFromMemory(bytes);
            //        bundleInfo = new AssetBundleInfo(bundle);
            //        bundleCache.Add(path, bundleInfo);
            //    }
            //    else
            //    {
            //        return null;
            //    }
            //}
            //else if (!cascade)
            //{
            //    bundleInfo.refCounter++;
            //}
            //return bundleInfo.bundle;
            return null;
        }

        public string GetFileName(string path)
        {
            int index = path.LastIndexOf("/");
            if (index >= 0)
            {
                return path.Substring(index + 1);
            }
            return path;
        }

        public string GetDirectoryName(string path)
        {
            int index = path.LastIndexOf("/");
            if (index > 0)
            {
                return path.Substring(0, index);
            }
            return "";
        }

        private string GetResourcePath(string path, string name)
        {
            string dirname = path.EndsWith(name) ? GetDirectoryName(path) : path;
            return string.IsNullOrEmpty(dirname) ? name : dirname + "/" + name;
        }
        private T LoadResource<T>(string path, string name) where T : UnityEngine.Object
        {
            T obj = null;
            AssetBundle bundle = LoadAssetBundle(path.ToLower() + ".assets", true);

            if (bundle != null)
            {
                obj = bundle.LoadAsset<T>(name);
            }

            if (obj == null)
            {
                string resource = GetResourcePath(path, name);
                obj = Resources.Load<T>(resource);
            }

            return obj;
        }

    }
}

